import rclpy
from rclpy.node import Node
from example_interfaces.msg import String
import threading
from queue import Queue
import time
import espeakng


class NovalSubReader(Node):
    "noval_sub_reader"

    def __init__(self, name):
        super().__init__(node_name=name)
        self.__que = Queue()
        self.__noval_subscriber = self.create_subscription(
            String, "noval_pub", self.sub_cb, 10
        )
        self.__speak_thd = threading.Thread(target=self.speak)
        self.__speak_thd.start()

    def sub_cb(self, msg):
        self.__que.put(msg.data)
        # self.get_logger().info(f"recieve:{msg.data}")

    def speak(self):
        self.get_logger().info(f"thd speaker start")
        speaker = espeakng.Speaker()
        speaker.voice = 'cmn-latn-pinyin'

        while rclpy.ok():
            if self.__que.empty():
                time.sleep(2)
            else:
                text = self.__que.get()
                self.get_logger().info(f"speak:{text}")
                speaker.say(text)
                speaker.wait()


def main():
    rclpy.init()
    node = NovalSubReader("novalsubspeaker")
    rclpy.spin(node)
    rclpy.shutdown()
